from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import redirect
from django.core.urlresolvers import reverse

from common.models import Product,Category,Shop,User

def index(request):
    pass

def add(request,pid):
    '''在购物车中放入菜品信息'''
    #获取要放入购物车中的菜品信息
    products = Product.objects.get(id=pid)
    food = products.toDict()
    food['m'] = 1 #添加一个购买量属性m
    #从session获取购物车信息，没有默认空字典
    foodlist = request.session.get('foodlist',{})
    #判断此菜品是否在购物车中
    if pid in foodlist:
        #菜品数量加
        foodlist[pid]['m']+=food['m']
    else:
        #新菜品添加
        foodlist[pid]=food

    #将购物车信息放回到session
    request.session['foodlist']=foodlist

    #重定向到首页
    return redirect(reverse('web_index'))

def delete(request,pid):
    '''删除一个菜品'''
    foodlist = request.session['foodlist']
    del foodlist[pid]
    request.session['foodlist']=foodlist
    return redirect(reverse('web_index'))

def clear(request):
    '''清空购物车'''
    request.session['foodlist'] = {}
    return redirect(reverse('web_index'))

def change(request):
    '''更改购物车中的菜品信息'''
    foodlist = request.session['foodlist']
    #获取信息
    foodid = request.GET.get('pid',0)
    num = int(request.GET.get('num',1))
    if num < 1:
        num = 1
    foodlist[foodid]['m'] = num #更改菜品数量
    request.session['foodlist'] = foodlist
    return redirect(reverse('web_index'))